<template>
  <div class="app-container">
    <!-- 导航栏 -->
    <el-header class="header">
      <div style="min-width: 1000px;">
        <MenuItem :menuTree="menuTree" :is-root="true"/>
      </div>
      <div class="nav-right">
        <el-input
            placeholder="搜索课程..."
            class="search-input"
            @click="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
        <el-dropdown v-if="isAuthenticated">
          <span class="el-dropdown-link">
            <el-avatar :size="40" :src="user?.avatar? baseURL+'user/download/'+user?.avatar:'/vite.svg'" />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="router.push('/profile')">个人中心</el-dropdown-item>
<!--              <el-dropdown-item>设置</el-dropdown-item>-->
              <el-dropdown-item divided @click="logout()">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button v-else type="primary" size="large" circle @click="router.push('/login')">登录</el-button>
      </div>
    </el-header>

    <!-- 主内容区 -->
    <el-main class="main-content">
      <router-view v-slot="{Component}" mode="out-in">
        <transition name="fade">
          <component :is="Component"/>
        </transition>
      </router-view>
    </el-main>
  </div>
</template>

<script setup>
import {computed, onMounted, ref, watch} from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import MenuItem from "@/components/MenuItem.vue";
import api from "@/api/index.js";
import  { buildMenuTree } from "@/utils/treeUtil"
import {useStore} from "vuex";

const router = useRouter()
const store = useStore()
const user = computed(() => store.getters?.currentUser)
const isAuthenticated = computed(() => store.getters?.isAuthenticated)
const menuTree = ref([{id:1,name:'加载中',url:'/',icon:'HomeFilled',children:[]}])
const userMap= ref(new Map())
// const test = "test"

watch(
  () => store.getters?.isAuthenticated,
  (newState, oldState) => {
    console.log('isAuthenticated改变了', newState, oldState)
    // if(store.state.token) {
    //   console.log('token存在')
    //   api.getInstance().defaults.headers.common['Authorization'] = 'Bearer ' + store.state.token
    // }
    if(newState){
      setTimeout(()=>{
        fetchMenuArch()
      },500)
    }else{
      menuTree.value = [{
        id: 1,
        url: '/recommendations',
        icon: 'View',
        name: '发现'
      }]
    }
  })
const logout = () => {
  api.logout(store.state.token).then(resp=>{
    menuTree.value = [{
      id: 1,
      url: '/recommendations',
      icon: 'View',
      name: '发现'
    }]
    store.commit('CLEAR_AUTH');
    router.push('/')
  })
}

const fetchMenuArch = () => {
  api.get('menu/authenticated/list').then(res => {
    menuTree.value = buildMenuTree(res.data)
  }).catch(e=>{
    menuTree.value = [{
      id: 1,
      url: '/recommendations',
      icon: 'View',
      name: '发现'
    }]
  })
}

const handleSearch = () => {
  router.push(`/search`)
}

const baseURL = api.getInstance().defaults.baseURL
onMounted(() => {
  if(store.getters.isAuthenticated)
    fetchMenuArch()
})
</script>

<style scoped>
.app-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f6ffed; /* 淡绿色背景 */
  border-bottom: 1px solid #e6e6e6;
  padding: 0 100px;
}

.nav-left {
  display: flex;
  align-items: center;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-input {
  width: 300px;
}

.el-menu-demo {
  background-color: transparent;
  border-bottom: none;
}

.el-menu--horizontal > .el-menu-item {
  height: 60px;
  line-height: 60px;
  color: #333;
}

.el-menu--horizontal > .el-menu-item.is-active {
  color: #a0d911;
  border-bottom: 2px solid #a0d911;
}

.main-content{
  background: linear-gradient(to bottom, rgb(246,255,237) , #ffffff 20%);
}

.main-content {
  flex: 1;
  padding: 0;
  background-color: #fafafa;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>